import os
import sys
import tempfile
import uuid
from pathlib import Path
from typing import List

import click
from dotenv import load_dotenv

from utils.pdf_to_png import convert_pdf_to_pngs
from utils.qiniu_uploader import QiniuUploader
from utils.win_picker import pick_pdf_file


@click.command()
@click.option("--dpi", default=200, show_default=True, help="Rasterization DPI for PNG output")
@click.option("--key-prefix", default="", help="Optional prefix for uploaded object keys, e.g. 'pdfs/'")
@click.option("--keep-local", is_flag=True, help="Keep local PNGs (skip cleanup)")
@click.option("--pdf", "pdf_path", default=None, help="Path to PDF (skip file picker)")
@click.option("--public", "public_bucket", is_flag=True, help="Bucket is public (skip tokenized URLs)")
@click.option("--output", "output_md", default=None, help="Output Markdown file path (defaults next to PDF)")
def main(dpi: int, key_prefix: str, keep_local: bool, pdf_path: str | None, public_bucket: bool, output_md: str | None) -> None:
	"""Convert PDF pages to PNG, upload to Qiniu, and write Markdown links to a file."""
	# Load .env from project root explicitly
	project_root = Path(__file__).resolve().parents[1]
	env_path = project_root / ".env"
	load_dotenv(dotenv_path=env_path, override=False)

	if pdf_path is None:
		selected = pick_pdf_file()
		if not selected:
			# No output to console per user request; just exit silently
			sys.exit(1)
		pdf_path = selected

	pdf_path = str(Path(pdf_path).resolve())
	if not os.path.isfile(pdf_path):
		# Silent exit on invalid input path
		sys.exit(1)

	# Determine output .md path
	base_name = Path(pdf_path).stem
	if output_md is None:
		output_path = Path(pdf_path).with_name(f"{base_name}.md")
	else:
		output_path = Path(output_md).resolve()

	# Prepare temp directory for PNGs
	temp_dir = tempfile.mkdtemp(prefix="pdf2md_")

	try:
		# 1) Convert PDF pages to PNG files
		png_paths: List[str] = convert_pdf_to_pngs(pdf_path=pdf_path, output_dir=temp_dir, dpi=dpi)
		if not png_paths:
			# Nothing to write
			return

		# 2) Upload to Qiniu
		uploader = QiniuUploader.from_env()
		uploaded_urls: List[str] = []
		for index, png_file in enumerate(png_paths, start=1):
			unique_suffix = uuid.uuid4().hex[:8]
			object_key = f"{key_prefix}{base_name}/{index:03d}_{unique_suffix}.png"
			url = uploader.upload_file(file_path=png_file, object_key=object_key, public=public_bucket)
			uploaded_urls.append(url)

		# 3) Write Markdown links to file
		lines = [f"![{base_name}]({url})" for url in uploaded_urls]
		output_path.write_text("\n".join(lines), encoding="utf-8")

	finally:
		# Optional cleanup
		if not keep_local:
			for p in Path(temp_dir).glob("*.png"):
				try:
					os.remove(p)
				except Exception:
					pass
			try:
				os.rmdir(temp_dir)
			except Exception:
				pass


if __name__ == "__main__":
	main()
